package com.jpa.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Li on 2016/3/11.
 */
public class TimeUtil {
    public static Map<String, Integer> intervalMap = new HashMap<String, Integer>();
    public static Map<String, String> intervalMapDateFormat = new HashMap<String, String>();
    public static Map<String, String> intervalMapDateFormatSqlForOra = new HashMap<String, String>();
    public static Map<String, String> intervalMapDateFormatSqlForMysql = new HashMap<String, String>();
    public static Map<String, String> intervalMapDateFormatSql = null;


    static {
        intervalMap.put("hr", Calendar.HOUR_OF_DAY);
        intervalMap.put("dy", Calendar.DAY_OF_MONTH);
        intervalMap.put("mi", Calendar.MINUTE);
        intervalMap.put("yr", Calendar.YEAR);
        intervalMap.put("mo", Calendar.MONTH);

        intervalMapDateFormat.put("hr", "yyyyMMddHH");
        intervalMapDateFormat.put("dy", "yyyyMMdd");
        intervalMapDateFormat.put("mi", "yyyyMMddHHmm");
        intervalMapDateFormat.put("yr", "yyyy");
        intervalMapDateFormat.put("mo", "yyyyMM");

        intervalMapDateFormatSqlForOra.put("hr", "yyyymmddhh24");
        intervalMapDateFormatSqlForOra.put("dy", "yyyymmdd");
        intervalMapDateFormatSqlForOra.put("mi", "yyyymmddhh24mi");
        intervalMapDateFormatSqlForOra.put("yr", "yyyy");
        intervalMapDateFormatSqlForOra.put("mo", "yyyymm");


        intervalMapDateFormatSqlForMysql.put("hr", "%Y%m%d%H");
        intervalMapDateFormatSqlForMysql.put("dy", "%Y%m%d");
        intervalMapDateFormatSqlForMysql.put("mi", "%Y%m%d%H%i");
        intervalMapDateFormatSqlForMysql.put("yr", "%Y");
        intervalMapDateFormatSqlForMysql.put("mo", "%Y%m");

    }

    public static Date parseTimeAccordingFormat(String value, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE);
        sdf.applyPattern(format);
        try {
            Date date = sdf.parse(value);
            return date;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String timeToStringAccordingFormat(Date time, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat("", Locale.SIMPLIFIED_CHINESE);
        sdf.applyPattern(format);
        String timeStr = sdf.format(time);
        return timeStr;
    }

    public static Date timeOperation(Date date, int interval, int value) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(interval, calendar.get(interval) + value);//让日期加1
        return calendar.getTime();
    }

}
